package com.lenovo.leos.filebrowser.netdisk;

import java.io.File;
import java.io.IOException;
import java.net.InterfaceAddress;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONException;
import org.xmlpull.v1.XmlPullParserException;
import com.lenovo.leos.filebrowser.R;
import android.app.Activity.OnTitleIconClickListener;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.XmlResourceParser;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lenovo.leos.filebrowser.engine.util.DirDefines;
import com.lenovo.leos.filebrowser.engine.util.FileUtil;
import com.lenovo.leos.filebrowser.engine.util.HzToPy;
import com.lenovo.leos.filebrowser.engine.util.MimeTypeParser;
import com.lenovo.leos.filebrowser.engine.util.MimeTypes;
import com.lenovo.leos.filebrowser.ui.BaseActivity;
import com.lenovo.leos.filebrowser.ui.Constant;
import com.lenovo.leos.filebrowser.ui.FileInterface;
import com.lenovo.leos.filebrowser.ui.TdActivity;
import com.lenovo.leos.letools.db.FileUploadEntity;
import com.lenovo.leos.letools.exception.NetException;
import com.lenovo.leos.letools.exception.PreUploadException;
import com.lenovo.leos.letools.lenovodata.UploadServer;

public class LenovoInterfaceActivity extends BaseActivity implements
		OnTitleIconClickListener, OnClickListener {

	private static final String TAG = "LenovoInterfaceActivity";
//	private UploadServer mFileSyncService;// 上传文件
	private ArrayList<String> fileAndDirs = new ArrayList<String>();
	
	FileSyncService mFileSyncService;

	private class Position {
		private static final String TAG = "Postion";

		private NetFile mfDir = null;
		private int miIndex = 0;

		public Position(int index, NetFile file) {
			if (0 > index || null == file || !file.isDirectory()) {
				if (TAG_FLAG)
					Log.e(TAG, "invalid parameter in Position");
				return;
			}
			miIndex = index;
			mfDir = file;
		}

		public void setIndex(int index) {
			if (0 > index) {
				if (TAG_FLAG)
					Log.e(TAG, "invalid index in setIndex");
				return;
			} else
				miIndex = index;
		}

		public int getIndex() {
			return miIndex;
		}

		public void setDir(NetFile file) {
			if (null == file || !file.isDirectory()) {
				if (TAG_FLAG)
					Log.e(TAG, "invalid parameter in setPosY");
				return;
			} else
				mfDir = file;
		}

		public NetFile getDir() {
			return mfDir;
		}

		public void dump() {
			if (TAG_FLAG) {
				Log.d(TAG, "===== Position Object Content =====");
				Log.d(TAG, "the index is: " + String.valueOf(miIndex));
				Log.d(TAG, "the dir is: " + mfDir.getAbsolutePath());
				Log.d(TAG, "===================================");
			}
		}
	};

	private static final String ZIP_MIMETYPE = "compressor/zip";// add xieqm
																// 110112

	private enum DISPLAYMODE {
		ABSOLUTE, RELATIVE
	};

	protected final int SUB_ACTIVITY_REQUEST_CODE = 1337;
	// private final String root = Constant.root;
	private final String root = "/";
	// private final String localroot = Constant.localroot;
	private final String sdroot = "/";
	// private LOCATION location = LOCATION.LOCAL;
	public static boolean isUDiskMnt = false;

	private final DISPLAYMODE displayMode = DISPLAYMODE.RELATIVE;

	/** Contains directories and files together */
	private List<NetFileItem> directoryEntries = new ArrayList<NetFileItem>();
	/** Dir separate for sorting */
	List<NetFileItem> mListDir = new ArrayList<NetFileItem>();
	/** Files separate for sorting */
	List<NetFileItem> mListFile = new ArrayList<NetFileItem>();
	/** SysDir separate for sorting */
	List<NetFileItem> mListSys = new ArrayList<NetFileItem>();

	private NetFile currentDirectory = NetDiskConstant.NET_DISK_ROOT;

	private static LinkedList<Position> sllPos = new LinkedList<Position>();

	public enum OPTYPE {
		CUT, COPY
	};

	public static OPTYPE opType;
	// the state of the progress in.
	public static int State;

	LenovoInterfaceAdapter itemList;
	private TextView tv = null;
	// add by PH 091011
	private static MimeTypes mMimeTypes = null;
	// end PH 091011
	// add by PH 091012
	public static final String ACTION_PICK_DIRECTORY = "org.openintents.action.PICK_DIRECTORY";
	// end PH 091012
	// add by PH 091013
	public static int officeFlag;
	String mInitDefaultPath;
	private ProgressDialog mProgressDialog;
	private MyBrowseToThread mBrowseToThread = null;
	private MyBrowseToThread mOperatorThread = null;
	MyBrowserToHandler mEH = null;
	private static final int SPACE_MSG = 50000;
	private static final int BROWSETO_RESULT_MSG = 40000;
	boolean browsetoThreadFlag = false;
	boolean SdcardUnmounted = false;
	TextView t;
	boolean mBrowseToThreadStop = false;
	ListView mlvContent;
	private Button bnsure, bncancle;

	private Position mpstCur = null;

	private static final boolean TAG_FLAG = true;
	public final static int RESULT_LIST = 12;
	private static LenovoInterfaceActivity instance = new LenovoInterfaceActivity();
	private static String projectState, uploadFileId;
	private AlertDialog dialog, renameDialog;
	private TextView sumSpace, remainingSpace;
	private String sSpace, sRemainingSpace;
	private String mUpload;
	private String[] uploadFile;
	private boolean[] uploadFileTypes;

	private NetDiskManager mndManager = null;

	List<NetFile> mlndItems = null;

	long mlCurOp = -1;

	public static LenovoInterfaceActivity getInstance() {
		return instance;
	}

	// private OnNotifyListener mntListener = new OnNotifyListener() {
	//
	// public void onOpNotify(Long opId, Bundle data) {
	// Log.i(TAG, "==> onOpNotify");
	//
	// if (opId == mlCurOp) {
	// ProgressMessageDialog.cancelDialog();
	// mndManager.unbindOpService();
	// }
	// }
	//
	// public void onServiceNotify(int msgId, String content) {
	// Log.i(TAG, "==> onServiceNotify");
	// Log.i(TAG, "the message is " + msgId);
	// }
	//
	// };

	private class MyBrowserToHandler extends Handler {
		public MyBrowserToHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			Log.i(TAG, "==> handleMessage");

			if (msg.what == BROWSETO_RESULT_MSG) {
				itemList.setListItems(directoryEntries);
				mlvContent.setAdapter(itemList);
				if (directoryEntries.size() == 0) {
					t.setText(R.string.not_found);
					t.setVisibility(View.VISIBLE);
				} else {
					t.setVisibility(View.GONE);

					if (null != mpstCur) {
						NetFile dir = mpstCur.getDir();
						if (dir.equals(currentDirectory)) {
							mlvContent.setSelection(mpstCur.getIndex());
						} else {
							mlvContent.setSelection(0);
						}
					} else {
						mlvContent.setSelection(0);
					}
				}
				browsetoThreadFlag = false;
				getSpace();
			} else if (msg.what == SPACE_MSG) {
				if (TAG_FLAG) {
					Log.d(TAG, "the sSpace is  =========" + sSpace);
					Log.d(TAG, "the remainingSpace is  ========="
							+ remainingSpace);
				}
				if (sSpace != null && sRemainingSpace != null) {
					ProgressMessageDialog.cancelDialog();
					sumSpace.setText(getString(R.string.total_size) + sSpace);
					remainingSpace.setText(getString(R.string.surplus_space)
							+ sRemainingSpace);
				}
			}// end
		}
	}

	private void getSpace() {
		if (TAG_FLAG) {
			Log.e(TAG, "==> getSpace");
		}
		mOperatorThread = new MyBrowseToThread(LenovoInterfaceActivity.this) {
			public void run() {

				long id = mndManager.getSpace();
				if (TAG_FLAG) {
					Log.i(TAG, "the id is ----------" + id);
				}

				NetDiskOpResult item = mndManager.getResult(id);
				try {
					while (item == null) {
						item = mndManager.getResult(id);
						try {
							Thread.sleep(100);
						} catch (InterruptedException e1) {
							e1.printStackTrace();
						}
					}
					sRemainingSpace = item.getFreespace();
					sSpace = item.getTotalspace();
					if (TAG_FLAG) {
						Log.d(TAG, "the getSpace sSpace is  ---------------"
								+ sSpace);
						Log.d(TAG,
								"the getSpace remainingSpace is  ----------------"
										+ remainingSpace);
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}
				mOperatorThread.onGetSpace();
			}
		};
		mOperatorThread.start();

	}

	private void initData() {
		if (null == sllPos) {
			sllPos = new LinkedList<Position>();
		} else
			sllPos.clear();
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		Log.e(TAG, "==> onCreate");

		super.onCreate(icicle);
		initState();
		mUpload = getIntent().getStringExtra("mUpload");
		uploadFile = getIntent().getStringArrayExtra("uploadFile");
		uploadFileTypes = getIntent().getBooleanArrayExtra("uploadFileTypes");
		if (TAG_FLAG) {
			Log.d(TAG, "the mUpload is ======" + mUpload);
			Log.d(TAG, "the uploadFile is ======" + uploadFile[0]);
			Log.d(TAG, "the uploadFileTypes is======" + uploadFileTypes[0]);
		}
		mndManager = NetDiskManager.getInstance(this);
		mndManager.bindOpService();
		// mndManager.setEnableNotify(true);
		// mndManager.setOnOpNotifyListener(mntListener);

		projectState = getIntent().getStringExtra("projectState");
		initData();
		if (TAG_FLAG) {
			Log.d(TAG, "the directoryEntries is -------------------"
					+ directoryEntries.size());
		}
		itemList = new LenovoInterfaceAdapter(this, this.directoryEntries);
		mEH = new MyBrowserToHandler(Looper.myLooper());
		this.customTitleIcon(0, 0, 0, this);
		initMimeTypes();
		
		Intent myintent = getIntent();
		mInitDefaultPath = myintent.getStringExtra("INIT_DEFAULT_PATH");
		browseToRoot();
		mlvContent.setSelection(0);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (TAG_FLAG)
			Log.e(TAG, "==> onResume");
		if (mndManager == null) {
			mndManager = NetDiskManager.getInstance(this);
			mndManager.bindOpService();
		}
		initState();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (browsetoThreadFlag) {
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
				mProgressDialog = null;
			}
		}
		if (null != dialog) {
			dialog.cancel();
		}
		if (null != renameDialog) {
			renameDialog.cancel();
		}

		if (null != mndManager) {
			mndManager.unbindOpService();
			mndManager = null;
		}

	}

	private void initState() {
		if (TAG_FLAG) {
			Log.e(TAG, "==> initState");
		}
		setContentView(R.layout.lenovo_interface);
		setTitle(R.string.lenovo);
		sumSpace = (TextView) findViewById(R.id.sumSpace);
		remainingSpace = (TextView) findViewById(R.id.remainingSpace);
		t = (TextView) findViewById(R.id.empty);
		tv = (TextView) findViewById(R.id.tv);
		bnsure = (Button) findViewById(R.id.bnsure);
		bncancle = (Button) findViewById(R.id.bncancle);
		bnsure.setOnClickListener(this);
		bncancle.setOnClickListener(this);
		
		mFileSyncService = FileSyncServiceManager.getInstance(this).doBindService();

		if (TAG_FLAG) {
			Log.d(TAG, "the currentDirectory is ============="
					+ currentDirectory);
		}
		setLocationText(currentDirectory.getAbsolutePath());
		if (sSpace != null && sRemainingSpace != null) {
			sumSpace.setText(getString(R.string.total_size) + sSpace);
			remainingSpace.setText(getString(R.string.surplus_space)
					+ sRemainingSpace);
		}
		mlvContent = (ListView) findViewById(android.R.id.list);
		mlvContent.setAdapter(itemList);

		// register a ContextMenu for the current listview
		mlvContent.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long id) {
				if (TAG_FLAG)
					Log.d(TAG, "==>setOnItemClickListener ");
				NetFile clickedFile = null;
				switch (LenovoInterfaceActivity.this.displayMode) {
				case RELATIVE:
				case ABSOLUTE:
					NetFileItem item = (NetFileItem) arg0.getAdapter().getItem(
							position);
					if (null != item) {
						NetFile nf = item.getFile();
						Log.i(TAG,
								"the clicked file is " + nf.getAbsolutePath());
						clickedFile = nf;
						uploadFileId = clickedFile.getID();
					}
					break;
				}
				// currentDirectory = clickedFile;
				Position pos = new Position(mlvContent
						.getFirstVisiblePosition(), currentDirectory);
				pos.dump();
				sllPos.addFirst(pos);
				mpstCur = null;
				if (clickedFile.isDirectory()) {
					LenovoInterfaceActivity.this.browseTo(clickedFile);
				}
			}
		});

		registerForContextMenu(mlvContent);
	}

	/**
	 * This function browses to the root-directory of the file-system.
	 */
	private void browseToRoot() {
		Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%browseRoot");

		if (null != NetDiskConstant.NET_DISK_ROOT) {
			browseTo(NetDiskConstant.NET_DISK_ROOT);
		} else {
			Toast.makeText(this, "can not get net disk root",
					Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * This function browses up one level according to the field:
	 * currentDirectory
	 */
	private void upOneLevel() {

		if ("/".equals(currentDirectory.getAbsolutePath())) {
			Intent intent = new Intent();
			intent.setClass(LenovoInterfaceActivity.this, TdActivity.class);
			intent.putExtra("projectState", projectState);
			startActivity(intent);
			if (null != mndManager) {
				mndManager.unbindOpService();
				mndManager = null;
			}
			finish();
		} else {
			String parent = this.currentDirectory.getParent();
			if (TAG_FLAG) {
				Log.d(TAG, " upOneLevel the parent is " + parent);
				Log.d(TAG, " upOneLevel the sdroot is " + sdroot);
			}
			if (parent != null) {
				if (parent.equals(root)) {
					parent = sdroot;
				}
				mpstCur = sllPos.poll();
				if (TAG_FLAG) {
					Log.d(TAG,
							" upOneLevel the mpstCur.getDir() is "
									+ mpstCur.getDir());
				}
				this.browseTo(mpstCur.getDir());
			}
		}
	}

	private class MyBrowseToThread extends Thread {

		Context mContext;
		boolean mStop = false;
		protected PowerManager.WakeLock mWakeLock;

		public MyBrowseToThread(Context context) {
			mContext = context;
			threadInt();
		}

		private void threadInt() {
			PowerManager powerManager = (PowerManager) mContext
					.getSystemService(Context.POWER_SERVICE);
			mWakeLock = powerManager.newWakeLock(
					PowerManager.SCREEN_DIM_WAKE_LOCK
							| PowerManager.ON_AFTER_RELEASE, TAG);
		}

		public void toStop() {
			mStop = true;
		}

		private void onBrowseToResult() {
			Message msg = mEH.obtainMessage(BROWSETO_RESULT_MSG, 0, 0, null);
			mEH.sendMessage(msg);
		}

		// add by xieqm 110324
		private void onGetSpace() {
			Message msg = mEH.obtainMessage(SPACE_MSG, 0, 0, null);
			mEH.sendMessage(msg);
		}
		// end
	}

	// private void browseTo(final String path) {
	private void browseTo(final NetFile nf) {
		Log.i(TAG, "==> browseTo");
		if (this.displayMode == DISPLAYMODE.RELATIVE) {

			// show waiting dialog
			ProgressMessageDialog.showMessageDialog(this,
					getString(R.string.lenovo_loading),
					getString(R.string.loading));

			currentDirectory = nf;
			uploadFileId = currentDirectory.getID();
			// final String path = "/";
			// send message to get dir content
			mBrowseToThread = new MyBrowseToThread(this) {
				public void run() {
					if (TAG_FLAG)
						Log.d(TAG,
								"******************** not equal file list ***********"
										+ mndManager.isConnected());
					// String path = "/";

					long id = -1;

					while (true) {
						if (mndManager.isConnected()) {
							id = mndManager.getDirContent(nf);
							break;
						} else {
							try {
								Thread.sleep(200);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}

					Log.d(TAG, "id gotten is " + id);

					NetDiskOpResult result = null;

					do {

						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						result = mndManager.getResult(id);

						if (null != result)
							break;
					} while (true);
					try {
						mlndItems = result.GetOnJSonItemListAll();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (TAG_FLAG) {
						Log.e(TAG, "the result is : " + result);
					}

					sortedFileList(mlndItems);

					mBrowseToThread.onBrowseToResult();

				}
			};
			mBrowseToThread.start();

			// If file is a directory,call fill() and browse it.
			if (nf.isDirectory()) {

				setLocationText(nf.getAbsolutePath());
			}
		}
	}

	private void setLocationText(String lt) {
		String relativePath = "";
		String[] strArr;
		String ln = "";
		String result = "";
		lt = Constant.textConvert(this, lt);
		relativePath = lt.replaceFirst(Constant.sdroot,
				getString(R.string.lenovo));
		relativePath = relativePath.trim();
		strArr = TextUtils.split(relativePath, "/");
		for (int i = 1; i < strArr.length; i++) {
			ln += ">" + strArr[i];
		}
		result = getString(R.string.lenovo) + ln;
		// int index = result.lastIndexOf(">");
		// if (result.length() > 30) {
		// result = "......" + result.substring(index, result.length());
		// Log.d(TAG, "the result is ---------------" + result);
		tv.setText(result);
		// } else {
		// if (result.equals(getString(R.string.lenovo))) {
		// tv.setText(result + ">");
		// } else {
		// tv.setText(result);
		// }
		// }
	}

	// add by PH 091011
	private void initMimeTypes() {
		if (mMimeTypes == null) {
			MimeTypeParser mtp = new MimeTypeParser();

			// XmlResourceParser in = getResources().getXml(
			// com.android.internal.R.xml.mimetypes);
			XmlResourceParser in = getResources().getXml(R.xml.mimetypes);
			try {
				mMimeTypes = mtp.fromXmlResource(in);
			} catch (XmlPullParserException e) {
				if (TAG_FLAG)
					Log.e(TAG,
							"************************** XmlPullParserException",
							e);
				throw new RuntimeException(
						"*************************** XmlPullParserException");
			} catch (IOException e) {
				if (TAG_FLAG)
					Log.e(TAG, "************************** IOException", e);
				throw new RuntimeException(
						"************************** IOException", e);
			}
		}
	}

	// end PH 091011

	// add by PH 091016
	HashMap<String, Drawable> mMimeIconMap;

	private Drawable getDrawableForMimetype(String mimetype) {
		Drawable icon = null;
		if (mMimeIconMap == null) {
			mMimeIconMap = new HashMap<String, Drawable>();
		}

		icon = mMimeIconMap.get(mimetype);
		if (icon == null) {
			PackageManager pm = getPackageManager();
			Intent intent = new Intent(Intent.ACTION_VIEW);
			// intent.setType(mimetype);
			intent.setDataAndType(Uri.fromParts("file", "", null), mimetype);

			List<ResolveInfo> lri = pm.queryIntentActivities(intent,
					PackageManager.MATCH_DEFAULT_ONLY);
			List<ResolveInfo> lriRe = pm.queryBroadcastReceivers(intent,
					PackageManager.MATCH_DEFAULT_ONLY);
			if (lri != null && lri.size() > 0) {
				icon = lri.get(0).loadIcon(pm);
			} else if (lriRe != null && lriRe.size() > 0) {
				icon = lriRe.get(0).loadIcon(pm);
			}

			if (icon != null) {
				mMimeIconMap.put(mimetype, icon);
			} else if (mimetype.equals(ZIP_MIMETYPE)) { // add 2010-12-13 by xqm
				icon = getResources().getDrawable(R.drawable.zip);
				mMimeIconMap.put(mimetype, icon);
			} else {
				icon = getResources().getDrawable(R.drawable.icon_unknown_file);
				mMimeIconMap.put(mimetype, icon);
			}
		}

		return icon;
	}

	private void addAllElements(List<NetFileItem> addTo,
			List<NetFileItem> addFrom) {
		// Log.d(TAG, "%%%%%%%%%%%%%%%%%%%%%%%%%addAllElements");
		for (int i = 0; i < addFrom.size(); i++) {
			addTo.add(addFrom.get(i));
		}
	}

	public static HzToPy mHz2Py = null;

	Comparator<NetFileItem> mSortWay = new Comparator<NetFileItem>() {
		public int compare(NetFileItem n1, NetFileItem n2) {
			int ret = 1;
			try {
				if (mHz2Py == null) {
					mHz2Py = new HzToPy(LenovoInterfaceActivity.this);
				}

				int i = 0;
				String sChar1 = null, sChar2 = null;
				while (true) {
					// if(browsetoThreadFlag && mBrowseToThread.mStop)
					// break;
					String sPy1 = n1.getCharPy(i);
					String sPy2 = n2.getCharPy(i);

					if (sPy1 == null && sPy2 == null) {
						if (i < n1.getText().length())
							sChar1 = n1.getText().substring(i, i + 1);
						else
							return -1;

						if (i < n2.getText().length())
							sChar2 = n2.getText().substring(i, i + 1);
						else
							return 1;

						if (sChar2.equalsIgnoreCase(sChar1)) {
							String sPy = mHz2Py.Char2Py(sChar1.charAt(0));
							n1.appendPy(sPy);
							n2.appendPy(sPy);
							continue;
						} else {
							n1.appendPy(mHz2Py.Char2Py(sChar1.charAt(0)));
							n2.appendPy(mHz2Py.Char2Py(sChar2.charAt(0)));
							continue;
						}
					} else if (sPy1 == null) {
						if (i < n1.getText().length())
							sChar1 = n1.getText().substring(i, i + 1);
						else
							return -1;

						sChar2 = n2.getText().substring(i, i + 1);
						if (sChar2.equalsIgnoreCase(sChar1)) {
							n1.appendPy(n2.getCharPy(i));
							continue;
						} else {
							n1.appendPy(mHz2Py.Char2Py(sChar1.charAt(0)));
							continue;
						}
					} else if (sPy2 == null) {
						if (i < n2.getText().length())
							sChar2 = n2.getText().substring(i, i + 1);
						else
							return 1;

						sChar1 = n1.getText().substring(i, i + 1);
						if (sChar1.equalsIgnoreCase(sChar2)) {
							n2.appendPy(n1.getCharPy(i));
							continue;
						} else {
							n2.appendPy(mHz2Py.Char2Py(sChar2.charAt(0)));
							continue;
						}
					} else {
						int nRet = sPy1.compareTo(sPy2);
						if (nRet == 0) {
							i += 1;
							continue;
						}

						return nRet;
					}
				}
			} catch (IOException e) {
				if (TAG_FLAG)
					Log.i(TAG,
							"**************catch a IOException in mHz2Py***************");
			}
			return ret;
		}
	};

	private void addIconifiedTextToList(NetFileItem item, List<NetFileItem> list) {
		int nIndex1 = 0;
		int nIndex2 = list.size() - 1;
		int nIndex = 0;

		if (nIndex2 < 0) {
			list.add(item);
			return;
		}

		while (true) {
			nIndex = (nIndex2 + nIndex1) / 2;
			NetFileItem temp = list.get(nIndex);

			int result = mSortWay.compare(item, temp);
			if (result > 0) {
				nIndex1 = nIndex + 1;
			} else if (result < 0) {
				nIndex2 = nIndex - 1;
			} else {
				list.add(nIndex, item);
				break;
			}

			if (nIndex1 > nIndex2) {
				if (result > 0) {
					if (nIndex >= list.size() - 1) {
						list.add(item);
					} else {
						list.add(nIndex + 1, item);
					}
				} else {
					list.add(nIndex, item);
				}

				break;
			}
		}
	}

	private void sortedFileList(List<NetFile> items) {

		if (items == null) {
			return;
		}

		// if(mBrowseToThread != null && mBrowseToThread.mStop)
		// return;
		Drawable currentUsrIcon = getResources().getDrawable(
				R.drawable.icon_default_folder);
		Drawable fileIcon = null;

		this.mListDir.clear();
		this.mListFile.clear();
		this.directoryEntries.clear();

		for (NetFile currentFile : items) {
			if (browsetoThreadFlag && mBrowseToThread.mStop)
				break;

			if (TAG_FLAG)
				Log.d(TAG,
						"currentFile.isDirectory()============================"
								+ currentFile.isDirectory());
			if (currentFile.isDirectory()) {
				addIconifiedTextToList(new NetFileItem(currentUsrIcon,
						currentFile, false), mListDir);
			} else {
				String fileName = currentFile.getName();
				String mimetype = mMimeTypes
						.getMimeType(fileName.toLowerCase());
				if (mimetype == null) {
					if (FileUtil.getExtension(fileName).equals(".p12")) {
						fileIcon = getResources().getDrawable(
								R.drawable.ic_menu_login);
					} else {
						fileIcon = getResources().getDrawable(
								R.drawable.icon_unknown_file);
					}
				} else {
					fileIcon = getDrawableForMimetype(mimetype);
				}

				switch (this.displayMode) {
				case ABSOLUTE:
				case RELATIVE:
					addIconifiedTextToList(new NetFileItem(fileIcon,
							currentFile, false), mListFile);
					break;
				}
			}
		}

		addAllElements(directoryEntries, mListDir);
		addAllElements(directoryEntries, mListFile);
	}

	public void exit() {
		System.exit(0);
	}

	public void onTitleIconClick() {
		if (TAG_FLAG)
			Log.e(TAG, "==> onTitleIconClick");
		upOneLevel();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK: {
			onTitleIconClick();
			return true;
		}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bnsure:
			if (TAG_FLAG) {
				Log.d(TAG, "the mUpload is ============" + mUpload);
				Log.d(TAG, "the uploadFile is ============" + uploadFile[0]);
				Log.d(TAG, "the uploadFileId is ============" + uploadFileId);
				Log.d(TAG, "the uploadFileTypes is ============"
						+ uploadFileTypes[0]);
			}
			if (null != mUpload && null != uploadFile && null != uploadFileId
					&& null != uploadFileTypes) {
				final Intent intent = new Intent();
//				mFileSyncService = new UploadServer(LenovoInterfaceActivity.this);
				for (int i = 0; i < uploadFile.length; i++) {
					fileAndDirs.add(uploadFile[i]);//将上传文件夹的路径全称（文件夹所在路径+文件名）
					checkNum();
					File upFile = new File(uploadFile[i]);
					long fileSize = upFile.length();
					boolean isEnough = checkNetSpace(fileSize);
					if(isEnough){
						return;
					}
					if (uploadFileTypes[i]) {
						if (TAG_FLAG) {
							Log.e(TAG, "start upload dir");
						}
						FileUploadEntity entity = mFileSyncService
								.getTaskByWholePath(uploadFile[i]);
						if (entity != null) {
							new AlertDialog.Builder(
									LenovoInterfaceActivity.this)
									.setTitle(R.string.remind)
									.setMessage(R.string.ishave)
									.setPositiveButton(
											R.string.dlg_btn_ok,
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													intent.setClass(
															LenovoInterfaceActivity.this,
															com.lenovo.leos.filebrowser.netdisk.TaskManagerActivity.class);
													startActivity(intent);
													finish();
												}
											})
									.setNegativeButton(
											R.string.alert_dialog_cancel,
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
												}

											}).show();
							return;
						}
						try {
							mFileSyncService.createDirTask(uploadFile[i],
									uploadFileId);
						} catch (NetException e) {
							new AlertDialog.Builder(
									LenovoInterfaceActivity.this)
									.setTitle(R.string.remind)
									.setMessage(R.string.net_error)
									.setPositiveButton(
											R.string.dlg_btn_ok,
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													finish();
												}
											}).show();
						} catch (PreUploadException e) {
							Toast.makeText(LenovoInterfaceActivity.this,
									e.getMessage(), Toast.LENGTH_SHORT).show();
						}
					} else {
						if (TAG_FLAG) {
							Log.e(TAG, "start upload file");
						}
						FileUploadEntity entity = mFileSyncService
								.getTaskByWholePath(uploadFile[i]);
						if (entity != null) {
							new AlertDialog.Builder(
									LenovoInterfaceActivity.this)
									.setTitle(R.string.remind)
									.setMessage(R.string.ishave)
									.setPositiveButton(
											R.string.dlg_btn_ok,
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													intent.setClass(
															LenovoInterfaceActivity.this,
															com.lenovo.leos.filebrowser.netdisk.TaskManagerActivity.class);
													startActivity(intent);
													finish();
												}
											})
									.setNegativeButton(
											R.string.alert_dialog_cancel,
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
												}

											}).show();
							return;
						}
						// 创建任务
						try {
							mFileSyncService.createTask(uploadFile[i],
									uploadFileId, null, null);
						} catch (NetException e) {
							new AlertDialog.Builder(
									LenovoInterfaceActivity.this)
									.setTitle(R.string.remind)
									.setMessage(R.string.net_error)
									.setPositiveButton(
											R.string.dlg_btn_ok,
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													finish();
												}
											}).show();
							return;
						} catch (PreUploadException e) {
							Toast.makeText(LenovoInterfaceActivity.this,
									e.getMessage(), Toast.LENGTH_SHORT).show();
						}
					}
				}

//				String mUpload = DirDefines.UPLOAD;
				intent.putExtra("projectState", projectState);
//				intent.putExtra("mUpload", mUpload);
				intent.putStringArrayListExtra("fileAndDirList", fileAndDirs);
				intent.setClass(
						LenovoInterfaceActivity.this,
						com.lenovo.leos.filebrowser.netdisk.TaskManagerActivity.class);
				startActivity(intent);

				if (null != mndManager) {
					mndManager.unbindOpService();
					mndManager = null;
				}
				finish();
			}

			break;
		case R.id.bncancle:
			finish();
			break;
		default:
			break;
		}
	}
	
	/**
	 * 超过20个任务弹出提示
	 */
	private void checkNum(){
		SumTask.getInstance().setContext(
				LenovoInterfaceActivity.this);
		int sumTask = SumTask.getInstance()
				.getSumTask();
		if (sumTask == SumTask.NUM) {
			Toast.makeText(LenovoInterfaceActivity.this,
					R.string.task_full,
					Toast.LENGTH_SHORT).show();
			return;
		}
	}
	
	/**
	 * 检测空间是否足够
	 */
	/**
	 * 检测空间是否足够
	 */
	private boolean checkNetSpace(long fileSize) {
		boolean isEnough = false;
		long netfreeSpace = 0;
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			netfreeSpace = SumTask.getInstance().getNetFreeSpace();
		}
		if (fileSize > netfreeSpace) {
			Toast.makeText(LenovoInterfaceActivity.this,
					getString(R.string.net_insufficient_space),
					Toast.LENGTH_SHORT).show();
			isEnough = true;
		}
		return isEnough;
	}

}
